const TOOLBAR = [{
		content: "招聘二维码",
		icon: "el-icon-platform-eleme",
		type: "primary",
		popover: "qr"
	},
	{
		content: "导出",
		icon: "el-icon-document-copy",
	},
]
const COLUMNS = [
	{
		prop: "addTime",
		label: "添加时间",
		width: "120"
	},

	{
		prop: "name",
		label: "姓名",
		width: "120"
	},
	{
		prop: "identityCard",
		label: "身份证号",
		width: "150"
	},
	{
		prop: "sex",
		label: "性别",
		width: "60"
	},

	{
		prop: "tel",
		label: "联系电话",
		width: "130"
	},

	{
		prop: "position",
		label: "应聘岗位",
		width: "100"
	},
	{
		prop: "salaryExpectation",
		label: "期望薪资",
		width: "100"
	},
	{
		prop: "fastestWorkTime",
		label: "最快到岗时间",
		width: "100"
	},

	{
		prop: "educationList",
		label: "学历",
		width: "80"
	},

	{
		prop: "remindTime",
		label: "提醒时间",
		width: "120"
	},
	{
		prop: "remake",
		label: "备注",
		width: "120"
	},
];



let app = new Vue({
	el: "#app",
	data() {
		var validatePassQuestionTotal = (rule, value, callback) => {
			setTimeout(() => {
				if (!Number.isInteger(Number(value))) {
					callback(new Error('请输入数字值'));
				} else {
					if (value > 20) {
						callback(new Error('题目数应该小于20'));
					} else if (value < 0) {
						callback(new Error('题目数应该大于0'));
					} else {
						callback();
					}
				}
			}, 1000);
		};

		var validatePassQuestionTotal2 = (rule, value, callback) => {
			setTimeout(() => {
				if (!Number.isInteger(Number(value))) {
					callback(new Error('请输入数字值'));
				} else {
					if (value != Number(this.testpaperForm.jianda) + Number(this.testpaperForm.danxuan) + Number(this.testpaperForm
							.duoxuan)) {
						callback(new Error('题目数应该等于单选多选简答数量'));
					} else {
						callback();
					}
				}
			}, 1000);
		};
		return {
			querydeptForm: {
				deptid: localStorage.getItem('DEPTID'),
			},

			// 所有团队人员
			members: [],
			remindrules: {
				remindTime: [{
						required: true,
						message: '请输入提醒时间',
						trigger: 'blur'
					},

				],
				remindContent: [{
					required: true,
					message: '请输入提醒内容',
					trigger: 'blur'
				}],
			},

			addtestpaperrules: {
				questionTotal: [{
						required: true,
						message: '请输入题目数',
						trigger: 'blur'
					},
					{
						validator: validatePassQuestionTotal,
						trigger: 'blur'
					},
					{
						validator: validatePassQuestionTotal2,
						trigger: 'blur'
					},
				],
				danxuan: [{
					required: true,
					message: '请输入单选数',
					trigger: 'blur'
				}],
				duoxuan: [{
					required: true,
					message: '请输入多选数',
					trigger: 'blur'
				}],
				jianda: [{
					required: true,
					message: '请输入简答数',
					trigger: 'blur'
				}],
				testType: [{
					required: true,
					message: '请输入类型',
					trigger: 'blur'
				}],
				name: [{
					required: true,
					message: '请输入姓名',
					trigger: 'blur'
				}],
				passMark: [{
					required: true,
					message: '请输入通过分数',
					trigger: 'blur'
				}],
			},
			// 所有部门
			depts: [],
			activeName: 'first',
			QR: 'this is QRurl',
			teamLink: 'Copy These Text！',
			queryname: [],
			queryidentityCard: [],
			timeout: null,
			//员工
			allusers: [],
			queryflag: 0,
			toolbar: TOOLBAR,
			localoptions: MYLOCALTYPE,
			options: MYPOSITIONTYPE,
			testpaperoptions: [],
			testpapersoptions: [],
			leftbar_show: true,
			// 添加、编辑标识
			action: "",
			tableHeight: window.innerHeight - 180,
			registrationQR: QRFIRSTCODE,
			tablecolums: COLUMNS,
			submitDisable: false,
			dialogExportFormVisible: false,
			createpaperDisable: false,
			dialogFormVisible: false,
			dialogpaperFormVisible: false,
			dialogdeptFormVisible: false,
			healthForm: [{
					"label": "是否患有严重的心脏疾病、高血压、哮喘等易突发性疾病？",
					"value": ""
				},
				{
					"label": "是否患有乙肝、肝炎、肺结核、艾滋等不适合参加公众密切交往的疾病?",
					"value": ""
				},
				{
					"label": "是否患有严重腰、颈椎疾病或近期做过重大手术?",
					"value": ""
				},
				{
					"label": "是否患有癌症、肿瘤等其他疾病?",
					"value": ""
				},
				{
					"label": "是否处于孕期、产期或哺乳期?或半年之内有生育计划?",
					"value": ""
				}
			],
			familyForm: [{
					"fam_relation": "",
					"fam_name": "",
					"fam_company_name": "",
					"fam_age": "",
					"fam_tel": ""
				},
				{
					"fam_relation": "",
					"fam_name": "",
					"fam_company_name": "",
					"fam_age": "",
					"fam_tel": ""
				}, {
					"fam_relation": "",
					"fam_name": "",
					"fam_company_name": "",
					"fam_age": "",
					"fam_tel": ""
				}
			],
			batchForm: {
				founddate: [],
			},
			workexperienceForm: [{
					"workstarttime": "",
					"workendtime": "",
					"companyname": "",
					"post": "",
					"workreferences": "",
					"workreferences_tel": "",
					"workreason": ""
				},
				{
					"workstarttime": "",
					"workendtime": "",
					"companyname": "",
					"post": "",
					"workreferences": "",
					"workreferences_tel": "",
					"workreason": ""
				}
			],
			accessForm: {

			},
			regForm: {
				identityCard: '',
				name: '',
				sex: '男',
				birthday: '',
				maritalStatus: '已婚',
				tel: '',
				registeredPermanentResidence: '',
				residentialAddress: '',
				urgentName: '',
				urgentTel: '',
				local: [],
				position: '',
				salaryExpectation: '',
				fastestWorkTime: '',
				learnStartTime: '',
				learnEndTime: '',
				schoolName: '',
				examinationType: '统考',
				educationList: '',
				major: '',
				graduateType: '毕业',
				passType: '未通过',
				openBank: '',
				accountNumber: '',
				remind: '提醒',
				remindTime: '',
				remindContent: '',
				invitees: '',
				source: '',
				inviteeDate: '',
				firstTester: '',
				ftComment: '',
				reTester: '',
				rtComment: ''

			},
			testpaperForm: {
				identityCard: '',
				name: '',
				examId: 0,
				questionTotal: '',
				danxuan: '',
				duoxuan: '',
				jianda: '0',
				totalScore: '',
				passMark: '',
				testType: '',
				stestType: '',
				testNumber: '1'
			},
			queryForm: {
				addTime: [],
				inviteeDate:[],
				updateTime: [],
				remindTime: [],
				local: [],
				position: "",
				name: "",
				perfectFlag: "",
				identityCard: '',
				pageNo: 1, // 当前页码
				pagesize: 100, // 每页记录数
				pagesizes: [10, 20, 50, 100]
			},
			testId: 0,
			pagetotal: 0,
			pagetotaltemp: 0,
			pickerOptions: {
				shortcuts: [{
					text: '最近一周',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近一个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
						picker.$emit('pick', [start, end]);
					}
				}, {
					text: '最近三个月',
					onClick(picker) {
						const end = new Date();
						const start = new Date();
						start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
						picker.$emit('pick', [start, end]);
					}
				}]
			},
			// 多选
			multipleSelection: [],
			pagedatatemp: [], // 当前页结果集
			pagedata: [], // 当前页结果集
			loaded: false,
		}
	},
	methods: {
		toolAction(acName) {
			if (acName == "招聘二维码") {
				this.QRcodeR()
			} else if (acName == "导出") {
				this.showDialogexport()
			}
		},
		showDialogexport() {
			this.dialogExportFormVisible = true;
		},
		async addbatch() {
			this.submitDisable = true;
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.put('api/myregistrator/export', this.batchForm, 'blob')
				if (res) {
					const blData = res //拿到blob数据
					const urlObjData = window.URL.createObjectURL(new Blob([res]))
					//获取文件 进行下转码	  
					name=this.batchForm.founddate[0]+"-"+this.batchForm.founddate[1]
					//const fileName = "hello.xls"
					const fileName =name+".xls"
					//创建a标签 点击a标签 达到下载目的
					const link = document.createElement('a')
					link.href = urlObjData
					link.download = fileName //下载文件的名字
					document.body.appendChild(link)
					link.click()

					document.body.removeChild(link)
					window.URL.revokeObjectURL(urlObjData);
				} else {
					this.$message.error("下载失败");
				}
				// if (res.code === 200) {
				// 	this.$message.success(res.message);
				// 	this.dialogExportFormVisible=false;
				// }else {
				// 	this.$message.error(res.message);
				// }

			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
			this.submitDisable = false;
		},

		changeremind() {
			if (this.regForm.remind === "不提醒") {
				this.regForm.remindTime = ''
				this.regForm.remindContent = ''
			}

		},
		handleClick(tab, event) {
			console.log(tab, event);
		},
		QRcodeR() {
			document.getElementById("applicant_registration").innerHTML = ''
			var qrcode = new QRCode(document.getElementById("applicant_registration"), {
				width: 100,
				height: 100
			});
			var href = QRFIRSTCODE
			qrcode.makeCode(href);
		},
		QRcode(index, row) {
			document.getElementById(index).innerHTML = ''
			var qrcode = new QRCode(document.getElementById(index), {
				width: 100,
				height: 100
			});
			var href = QRCODE + "cardid=" + row.identityCard
			qrcode.makeCode(href);
		},

		tableRowClassName({
			row,
			rowIndex
		}) {
			if (this.pagedata[rowIndex].remind == "提醒" && this.pagedata[rowIndex].remindFlag == true) {
				return 'warning-row';
			} else if (this.pagedata[rowIndex].remindFlag == '已完善') {
				return 'success-row';
			}
			return '';
		},

		copyregistratorlink(index, row) {
			var href = QRCODE + "cardid=" + row.identityCard
			this.teamLink = href;
			this.copy(index, row);
		},
		copy(index, row) {
			this.$copyText(this.teamLink).then(e => {
				this.$message({
					message: '复制成功！',
					type: 'success'
				})
			}, e => {
				this.$message({
					message: '复制失败！',
					type: 'error'
				})
			})
		},


		// 显示侧边栏
		showLeftBar() {

			if (this.leftbar_show)
				return this.leftbar_show = false
			if (!this.leftbar_show)
				return this.leftbar_show = true

		},
		// 表格多选 
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		handleRemove(file, filelist) {},

		handleAvatarSuccess(res, file, filelist) {},



		// 检查数据是否有修改
		checkDataChanged() {
			// 比对数据有无发生变化
			for (let key in this.regForm) {
				if (this.regForm[key] != this.regFormOrg[key]) {
					return true;
				}
			}
			return false;
		},
		getscore() {
			this.testpaperForm.questionTotal = parseInt(this.testpaperForm.danxuan) + parseInt(this.testpaperForm.duoxuan) +
				parseInt(this.testpaperForm.jianda)
			this.testpaperForm.totalScore = (parseInt(this.testpaperForm.questionTotal) - parseInt(this.testpaperForm.jianda)) *
				5
		},

		// 确认
		async createpaperconfirm() {
			this.createpaperDisable = true;
			this.$refs.testpaperForm.validate(async valid => {
				if (valid) {
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = await axios.put('api/testpaperview/addpaper', this.testpaperForm);
						this.testId = res.data[0]
						if (res.code === 200) {
							this.dialogpaperFormVisible = false
							this.$message.success(res.message);
						} else {
							this.$message.error(res.message);
						}
					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}
					// 关闭加载框
					loading.close();
				}
			})
			this.createpaperDisable = false;
		},
		// 取得所有部门列表
		async getAllDept() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/alldept');
				if (res.code === 200) {
					this.depts = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
		},
		// 确认
		async confirm() {
			this.submitDisable = true;
			this.$refs.regForm.validate(async valid => {
				if (valid) {
					const loading = this.$loading(LOAD_STYLE);
					try {
						let res = await axios.put('api/myregistrator/update', this.regForm);
						if (res.code === 200) {
							this.query();
							this.dialogFormVisible = false
						} else {
							this.$message.error(res.message);
						}

					} catch (e) {
						this.$message.error('请求出错！', e.message);
					}

					// 关闭加载框
					loading.close();
				}
			})

			this.submitDisable = false;
		},
		start() {
			this.queryForm.pageNo = 1
			this.query()
		},

		// 查询
		async query() {
			this.submitDisable = true;
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.post('api/registration/querylist', this.queryForm);
				if (res.code === 200) {
					this.pagedata = res.data;
					this.pagetotal = res.total;
					for (let item in this.pagedata) {
						this.pagedata[item].health = this.pagedata[item].health == null ? this.healthForm : JSON.parse(this.pagedata[
							item].health)
						this.pagedata[item].workexperience = this.pagedata[item].workexperience == null ? this.workexperienceForm :
							JSON.parse(this.pagedata[item].workexperience)
						this.pagedata[item].family = this.pagedata[item].family == null ? this.familyForm : JSON.parse(this.pagedata[
							item].family)
					}

					this.$message.success(res.message);

				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}

			// 关闭加载框
			loading.close();
			this.submitDisable = false;
		},

		// 查询
		async queryall() {
			this.submitDisable = true;
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				this.queryFormAll = deepCopy(this.queryForm)
				let res = await axios.post('api/registration/querylist', this.queryFormAll);
				if (res.code === 200) {
					this.pagedatatemp = res.data;
					this.pagetotaltemp = res.total;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			let arr = [];
			for (let item in this.pagedatatemp) {
				arr.push({
					value: this.pagedatatemp[item].name
				})
			}
			this.queryname = arr;

			let arridentityCard = [];
			for (let item in this.pagedatatemp) {
				arridentityCard.push({
					value: this.pagedatatemp[item].identityCard
				})
			}
			this.queryidentityCard = arridentityCard;
			// 关闭加载框
			loading.close();
			this.submitDisable = false;
		},

		selectionChange(selection) {
			this.selection = selection
		},
		//生成试卷
		generatetestpaper(index, row) {
			console.log("hello,i will give a radom test paper")
			this.dialogpaperFormVisible = true
			this.testpaperForm.identityCard = row.identityCard
			this.testpaperForm.name = row.name
		},
		async getAllUser() {
			// 显示加载框
			const loading = this.$loading(LOAD_STYLE);
			try {
				let res = await axios.get('api/user/all');
				if (res.code === 200) {
					this.allusers = res.data;
				} else {
					this.$message.error(res.message);
				}
			} catch (e) {
				this.$message.error('取得所有用户列表请求出错！', e.message);
			}
		
			// 关闭加载框
			loading.close();
		
		},
		//准入
		async accessuserinfo() {
			try {
				let res = await axios.post('api/myregistrator/adduser', this.accessForm);
				if (res.code === 200) {

					this.$message({
						type: 'success',
						message: '信息填入成功!'
					});
				} else {
					this.$message.error(res.message);
				}

			} catch (e) {
				this.$message.error('请求出错！', e.message);
			}
			dialogdeptFormVisible = false
		},
		//准入部门输入
		accessdept(index, row) {
			this.index = index;
			this.dialogdeptFormVisible = true;
			this.accessForm = deepCopy(row)
			//
			console.log(this.accessForm)
		},
		//准入提示
		access(index, row) {
			this.$confirm('此操作将录入该员工信息, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.accessuserinfo()
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消准入'
				});
			});
		},
		// 编辑
		edit(index, row) {
			this.action = "edit"
			this.index = index;
			this.dialogFormVisible = true;
			this.regForm = deepCopy(row)
			// 保留原始数据，方便比对
			this.regFormOrg = deepCopy(row)
		},
		// 设定表格当前页
		handleCurrentPageChange(selectedPageNo) {
			this.queryForm.pageNo = selectedPageNo
			// 加载数据页
			this.query()
		},
		//设定每页记录数
		handleSizeChange(val) {
			this.queryForm.pagesize = val
			// 加载数据页
			this.query()
		},

		querySearchAsyncName(queryString, cb) {
			var queryname = this.queryname;
			var results = queryString ? queryname.filter(this.createStateFilter(queryString)) : queryname;
			clearTimeout(this.timeout);
			this.timeout = setTimeout(() => {
				cb(results);
			}, 3000 * Math.random());
		},
		querySearchAsyncIDcard(queryString, cb) {
			var queryidentityCard = this.queryidentityCard;
			var results = queryString ? queryidentityCard.filter(this.createStateFilter(queryString)) : queryidentityCard;
			clearTimeout(this.timeout);
			this.timeout = setTimeout(() => {
				cb(results);
			}, 3000 * Math.random());
		},
		createStateFilter(queryString) {
			return (state) => {
				return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
			};
		},
		handleSelect(item) {
			console.log(item);
		},
		async initTestTypes() {
			try {
				let res = await axios.get('api/test/inittype');
				if (res.code === 200) {
					this.testpaperoptions = res.data
				} else {
					this.$toast("题库大分类取得出错。");
				}
			} catch (e) {
				this.$toast("网络连接异常。");
			}
		},
		async initTestSubTypes(type) {
			try {
				let res = await axios.get('api/test/initsubtype/' + type);
				if (res.code === 200) {
					this.testpapersoptions = res.data
				} else {
					this.$toast("题库小分类取得出错。");
				}
			} catch (e) {
				this.$toast("网络连接异常。");
			}
		},
		changeType(value) {
			this.initTestSubTypes(value);
		}
	},

	async mounted() {
		//初始化员工列表
		this.getAllUser();
		// 初始化部门列表
		this.getAllDept();
		//远程查询名字身份证
		//this.queryall();
		// 自动调整表格高度
		window.onresize = () => {
			return (() => {
				this.tableHeight = window.innerHeight - 180
			})()
		}
		this.initTestTypes();
		this.initTestSubTypes("None");


	}

});
